package com.neuedu.yyzx.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.neuedu.yyzx.po.User;

/**
 * @author 金山
 * 项目：yyzx
 * site: https://blog.fulfill.com.cn
 * 描述
 * @data 2025/3/288:55
 */
public class JWTUtils {

    // jwt 秘钥
    private static String secret = "adsafsafdsafdsafdsadsadsafdsafsafsafsafafa";

    public static String create(User user) {

        String jwtToken = JWT.create()

                .withClaim("id", user.getId())
                .withClaim("username", user.getUsername())
                .withClaim("nickname", user.getNickname())
                .withClaim("lastlogin", user.getLastlogin())
                // 加密
                .sign(Algorithm.HMAC256(secret));

        return jwtToken;

    }

    /**
     * 验证token是否有效
     *
     * @param token
     * @return
     */
    public static boolean verify(String token) {
        boolean success = false;


        try {
            JWTVerifier require = JWT.require(Algorithm.HMAC256(secret)).build();
            // 如果不报错，证明 token的格式 没问题
            DecodedJWT decodedJWT = require.verify(token);
            success = true;
        } catch (Exception e) {
        }


        return success;
    }


    /**
     * 获取Token中UserId
     *
     * @param token
     * @return
     */
    public static Long getUserId(String token) {

        Long userId = null;
        try {
            JWTVerifier require = JWT.require(Algorithm.HMAC256(secret)).build();
            // 如果不报错，证明 token的格式 没问题
            DecodedJWT decodedJWT = require.verify(token);
            userId = decodedJWT.getClaim("id").asLong();
        } catch (Exception e) {
        }


        return userId;
    }

}
